let timer;

function request(url, method, params, header, successCallback, failCallback) {
  header = header || {};
  header.authorization = 'Basic d3gtYXV0aC0xMjM6d3gtYXV0aC00NTY=';
  timer = setTimeout(() => {
    wx.showLoading({})
  }, 500)
  setTimeout(() => {
    wx.hideLoading()
  }, 1000);
  //可以做加密处理
  let paramsData = params;
  params.accessToken = wx.getStorageSync('accessToken') ? wx.getStorageSync('accessToken') : '';
  params.accessUserId = wx.getStorageSync('accessUserId') ? wx.getStorageSync('accessUserId') : '';
  wx.request({
    url: url,
    data: params || {},
    method: method || 'get',
    //设置header
    // header: { 'content-type': 'application/x-www-form-urlencoded' },post
    // 'content-type': 'application/json' // 默认值
    header: header,
    success: (res) => {
      clearTimeout(timer);
      wx.hideLoading();
      //处理 res.code
      if (res.data.code == 0) {
        //正常
        successCallback(res);

      } else if (res.data.code == 1) {
        wx.showToast({
          title: '请求错误',
        })
      }
      else if (res.data.code == 2) {
        //提示
        wx.showModal({
          title: '温馨提示',
          content: `${res.data.message}`,
          confirmColor: '#ff474f'
        })
      }


    },
    fail: (err) => {
      // console.log(err);
      clearTimeout(timer);
      wx.hideLoading();
      wx.showToast({
        title: '响应失败',
      })
      failCallback(err)
    },
    //不管是成功还是失败都要执行的函数
    complete: () => {

    }

  });
}

export const ajax = {
  get: (url, params, header, successCallback, failCallback) => {
    request(url, 'get', params, {'content-type': 'application/json'}, successCallback, failCallback)
  },
  post: (url, params, header, successCallback, failCallback) => {
    request(url, 'post', params, {'content-type': 'application/x-www-form-urlencoded'}, successCallback, failCallback)
  }
};
